package com.zym.init.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zym.init.configuration.PasswordConfiguration;
import com.zym.init.enums.UserStatusEnum;
import com.zym.init.mapper.UserMapper;
import com.zym.init.model.domain.User;
import com.zym.init.model.vo.UserVo;
import com.zym.init.service.UserService;
import com.zym.init.utils.ValidatorUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author zouyangming
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-10-15 16:46:17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final PasswordConfiguration passwordConfiguration;
    private final UserMapper userMapper;

    public UserServiceImpl(PasswordConfiguration passwordConfiguration, UserMapper userMapper) {
        this.passwordConfiguration = passwordConfiguration;
        this.userMapper = userMapper;
    }

    /**
     * 新增用户
     *
     * @param user 用户对象
     * @return 新增结果
     */
    @Override
    public boolean insertUser(User user) {
        if (BeanUtil.isEmpty(user)) {
            return false;
        }
        if (selectUserByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户已存在");
        }
        // 校验用户名和密码是否合法
        ValidatorUtils.checkUsername(user.getUsername());
        ValidatorUtils.checkPassword(user.getPassword());
        // 加密密码
        String encryptedPassword = SaSecureUtil.aesEncrypt(passwordConfiguration.getEncrypted(), user.getPassword());
        // 新增用户
        User newUser = new User();
        newUser.setUsername(user.getUsername());
        newUser.setPassword(encryptedPassword);
        return this.save(newUser);
    }

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User selectUserByUsername(String username) {
        if (!StringUtils.hasLength(username)) {
            return null;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = this.getOne(wrapper);
        if (BeanUtil.isNotEmpty(user)) {
            return user;
        }
        return null;
    }

    /**
     * 根据用户名和密码查询用户
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户对象
     */
    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            throw new RuntimeException("用户名或密码不能为空");
        }
        // 查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = this.getOne(wrapper);
        if (BeanUtil.isEmpty(user)) {
            throw new RuntimeException("用户不存在");
        }
        // 解密密码
        String encryptedPassword = SaSecureUtil.aesEncrypt(passwordConfiguration.getEncrypted(), password);
        if (encryptedPassword.equals(user.getPassword())) {
            return user;
        } else {
            throw new RuntimeException("密码错误");
        }
    }

    /**
     * 根据用户id查询用户
     *
     * @param userId 用户id
     * @return 用户对象
     */
    @Override
    public UserVo selectUserVoById(Long userId) {
        User user = getById(userId);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);
        return userVo;
    }

    /**
     * 检查用户是否已被封禁
     *
     * @param userId 用户id
     * @return true：已被封禁；false：未被封禁
     */
    @Override
    public boolean checkUserIsBanned(Long userId) {
        UserStatusEnum userStatusEnum = selectUserStatus(userId);
        return userStatusEnum == UserStatusEnum.BANNED || userStatusEnum == UserStatusEnum.SUSPENDED;
    }

    /**
     * 查询用户状态
     *
     * @param userId 用户id
     * @return 用户状态
     */
    @Override
    public UserStatusEnum selectUserStatus(Long userId) {
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.select(User::getStatus);
        lqw.eq(User::getUserId, userId);
        User user = userMapper.selectOne(lqw);
        return UserStatusEnum.getEnumByStatus(user.getStatus());
    }

    /**
     * 更新用户最后登录时间
     *
     * @return 更新结果
     */
    @Override
    public boolean updateUserLastLoginTime(Long userId) {
        User user = new User();
        user.setUserId(userId);
        user.setLastLoginTime(new Date());
        return updateById(user);
    }


}




